import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useCartStore = defineStore(
  'cart',
  () => {
    // 购物车的商品列表
    const cartList = ref([])

    // 重新给购物车列表赋值
    const resetCartList = newValue => {
      cartList.value = newValue
    }
    // 清空购物车列表
    const clearCartList = () => {
      cartList.value = []
    }

    // 添加商品信息到购物车列表
    const pushGoods = goods => {
      cartList.value.push(goods)
    }

    /**
     * 删除购物车商品
     * @params {number} id - 传入skuId以便精准删除该商品
     */
    const delGoods = id => {
      const index = cartList.value.findIndex(item => item.skuId === id)
      cartList.value.splice(index, 1)
    }
    // 计算总商品数量和总商品价格
    const totalCount = computed(() => {
      return cartList.value.reduce((pre, next) => {
        return pre + next.count
      }, 0)
    })
    const totalPrice = computed(() => {
      return cartList.value.reduce((pre, next) => {
        return pre + next.count * next.price
      }, 0)
    })
    // 是否全选
    const isCheckAll = computed(() => {
      return !cartList.value.some(item => item.selected === false)
    })
    // 全选所有单选框
    const checkAll = e => {
      cartList.value.forEach(item => (item.selected = e))
    }
    // 计算勾选商品的总数量和价格
    const checkedCount = computed(() => {
      return cartList.value.reduce((pre, next) => {
        if (next.selected) {
          return pre + next.count
        }
        return pre
      }, 0)
    })
    const checkedPrice = computed(() => {
      return cartList.value.reduce((pre, next) => {
        if (next.selected) {
          return pre + next.count * next.price
        }
        return pre
      }, 0)
    })

    return {
      cartList,
      resetCartList,
      pushGoods,
      delGoods,
      totalCount,
      totalPrice,
      isCheckAll,
      checkAll,
      checkedCount,
      checkedPrice,
      clearCartList,
    }
  },
  {
    persist: true,
  }
)
